export default {
  namespaced: true,
  state: () => ({
    cart: JSON.parse(uni.getStorageSync('cart') || '[]')  
  }),
  
  mutations: {
    addToCart(state, goods) {
      // 根据提交的商品的 id 查询购物车中是否存在这件商品,如果不存在则返回 undefined
      const findResult = state.cart.find((x) => x.goods_id === goods.goods_id)
      if (!findResult) {
        // 购物车内没有这件商品,直接添加
        state.cart.push(goods)
      } else {
        // 已在购物车中存在,只更新数量
        findResult.goods_count ++
      }
      // 通过 commit 方法,调用 m_cart 命名空间下的 saveToStorage 方法
      this.commit('m_cart/saveToStorage')
    },
    saveToStorage(state) {
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    updateGoodsState(state, goods) {
      const findResult = state.cart.find((x) => x.goods_id === goods.goods_id)
      if (findResult) {
        findResult.goods_state = goods.goods_state
        this.commit('m_cart/saveToStorage')
      }
    },
    updateGoodsCount(state, goods) {
      const findResult = state.cart.find((x) => x.goods_id === goods.goods_id)
      if (findResult) {
        findResult.goods_count = goods.goods_count
        this.commit('m_cart/saveToStorage')
      }
    },
    updateGoods(state, goods_id) {
      state.cart = state.cart.filter((x) => x.goods_id !== goods_id)
      this.commit('m_cart/saveToStorage')
    },
    updateCheckState(state, goods_state) {
      state.cart.forEach((item) => item.goods_state = goods_state)
      this.commit('m_cart/saveToStorage')
    }
  },
  
  getters: {
    total(state) {
      let c = 0
      state.cart.forEach(goods => c += goods.goods_count )
      return c
    },
    // 勾选商品的总数量
    checkCount(state) {
      return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
    },
    // 勾选商品的总价格
    chekedGoodsAmount(state) {
      return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count * item.goods_price, 0)
    }
  }
}